package com.project.common.core.utils.tencentyun;

import com.alibaba.fastjson.JSONObject;
import com.project.common.core.config.prop.PropAttributes;
import com.project.common.core.config.prop.PropConfig;
import com.project.common.core.utils.HttpUtil;
import com.project.common.core.utils.tencentyun.vo.*;
import com.tencentyun.TLSSigAPIv2;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 腾讯IM工具类
 *
 * @author wyy
 * @date 2021-02-21 14:38
 */
@Component
public class IMUtil {
    /**
     * 日志对象
     */
    private static final Logger log = LoggerFactory.getLogger(IMUtil.class);
    public static final String IM_ADMIN = "admin";

    /**
     * 单发单聊消息
     */
    public static final String IM_SEND_MSG_URL = "https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=SDKAPPID&identifier=IDENTIFIER&usersig=USERSIG&random=RANDOM&contenttype=json";
    public static final String IM_BATCH_SEND_MSG_URL = "https://console.tim.qq.com/v4/openim/batchsendmsg?sdkappid=SDKAPPID&identifier=IDENTIFIER&usersig=USERSIG&random=RANDOM&contenttype=json";

    /**
     * 发送单聊文本消息
     *
     * @param To_Account       接收消息方
     * @param SyncOtherMachine 1：把消息同步到 From_Account 在线终端和漫游上；
     *                         2：消息不同步至 From_Account；
     * @return
     */
    public static ResponseVo sendMsgOfTxt(String To_Account, Integer SyncOtherMachine, String msgTxt) {
        // 初始化单发单聊消息URL
        String appId = PropConfig.getProperty(PropAttributes.THIRDPARTY_TENCENTYUN_IM_APPID);
        String key = PropConfig.getProperty(PropAttributes.THIRDPARTY_TENCENTYUN_IM_SECRET);
        TLSSigAPIv2 api = new TLSSigAPIv2(Long.parseLong(appId), key);
        String userSig = api.genUserSig(IM_ADMIN, 180 * 86400);
        String url = IM_SEND_MSG_URL.replace("SDKAPPID", appId)
                .replace("IDENTIFIER", IM_ADMIN)
                .replace("USERSIG", userSig)
                .replace("RANDOM", String.valueOf(RandomUtils.nextInt()));

        // 初始化消息内容
        MsgContentVo msgContentVo = new MsgContentVo();
        msgContentVo.setText(msgTxt);

        // 初始化消息包体
        MsgBodyVo msgBodyVo = new MsgBodyVo();
        msgBodyVo.setMsgType("TIMTextElem");
        msgBodyVo.setMsgContent(msgContentVo);

        // 初始化文本消息
        SendMsgReqVo sendMsgReqVo = new SendMsgReqVo();
        sendMsgReqVo.setTo_Account(To_Account);
        if (null == SyncOtherMachine) {
            sendMsgReqVo.setSyncOtherMachine(2);
        } else {
            sendMsgReqVo.setSyncOtherMachine(SyncOtherMachine);
        }
        sendMsgReqVo.setMsgRandom(RandomUtils.nextInt());
        sendMsgReqVo.setMsgTimeStamp(Integer.valueOf(String.valueOf(System.currentTimeMillis() / 1000)));
        List<MsgBodyVo> msgBodyVoList = new ArrayList<>();
        msgBodyVoList.add(msgBodyVo);
        sendMsgReqVo.setMsgBody(msgBodyVoList);

        // 消息转化为JSON
        String msgJson = JSONObject.toJSONString(sendMsgReqVo);
        log.info("\r\n *******发送单聊消息:{}:{}", url, msgJson);

        String resJson = HttpUtil.httpsPost(url, msgJson);
        if (StringUtils.isBlank(resJson)) {
            return null;
        }
        ResponseVo responseVo = JSONObject.parseObject(resJson, new ResponseVo().getClass());

        return responseVo;
    }

    /**
     * 发送单聊群发文本消息
     *
     * @param To_Account       接收消息方
     * @param SyncOtherMachine 1：把消息同步到 From_Account 在线终端和漫游上
     *                         2：消息不同步至 From_Account；
     * @return
     */
    public static ResponseVo batchSendMsgOfTxt(List<Object> To_Account, Integer SyncOtherMachine, String msgTxt) {
        // 初始化单发单聊消息URL
        String key = PropConfig.getProperty(PropAttributes.THIRDPARTY_TENCENTYUN_IM_SECRET);
        String appId = PropConfig.getProperty(PropAttributes.THIRDPARTY_TENCENTYUN_IM_APPID);
        TLSSigAPIv2 api = new TLSSigAPIv2(Long.parseLong(appId), key);
        String userSig = api.genUserSig(IM_ADMIN, 180 * 86400);
        String url = IM_BATCH_SEND_MSG_URL.replace("SDKAPPID", appId)
                .replace("IDENTIFIER", IM_ADMIN)
                .replace("USERSIG", userSig)
                .replace("RANDOM", String.valueOf(RandomUtils.nextInt()));

        // 初始化消息内容
        MsgContentVo msgContentVo = new MsgContentVo();
        msgContentVo.setText(msgTxt);

        // 初始化消息包体
        MsgBodyVo msgBodyVo = new MsgBodyVo();
        msgBodyVo.setMsgType("TIMTextElem");
        msgBodyVo.setMsgContent(msgContentVo);

        // 初始化文本消息
        BatchSendMsgReqVo sendMsgReqVo = new BatchSendMsgReqVo();
        sendMsgReqVo.setTo_Account(To_Account);
        if (null == SyncOtherMachine) {
            sendMsgReqVo.setSyncOtherMachine(2);
        } else {
            sendMsgReqVo.setSyncOtherMachine(SyncOtherMachine);
        }
        sendMsgReqVo.setMsgRandom(RandomUtils.nextInt());
        List<MsgBodyVo> msgBodyVoList = new ArrayList<>();
        msgBodyVoList.add(msgBodyVo);
        sendMsgReqVo.setMsgBody(msgBodyVoList);

        // 消息转化为JSON
        String msgJson = JSONObject.toJSONString(sendMsgReqVo);
        log.info("\r\n *******发送批量单聊消息:{}-------->{}", msgJson, To_Account.toString());

        String resJson = HttpUtil.httpsPost(url, msgJson);
        if (StringUtils.isBlank(resJson)) {
            return null;
        }
        ResponseVo responseVo = JSONObject.parseObject(resJson, new ResponseVo().getClass());

        return responseVo;
    }

    public static void main(String[] args) {
        System.out.println(RandomUtils.nextInt());
    }

}
